<script setup lang="ts">
  import {
    getDept,
    editDept,
    getOrgAll,
    getUserList,
    delectUser,
    getAllRole,
  } from '@/api/syssetting';
  import {
    findIdByKey,
    transformDeptTree,
    transformDeptTreeSelect,
  } from '@/utils/utils';
  import useLoading from '@/hooks/useLoading';
  import { Message, Modal, TableInstance } from '@arco-design/web-vue';
  import { omit } from 'lodash';
  import { ref } from 'vue';
  import Edit from './edit/index.vue';
  import Add from './add/index.vue';
  import Rpwd from './rpwd/index.vue';
  const proTableRef = ref<TableInstance | null>(null);

  const visible = ref(false);
  const visible1 = ref(false);
  const visible2 = ref(false);
  defineOptions({ name: 'userSettingUser' });
  const { loading, setLoading } = useLoading(false);
  const currentKeys = ref();
  setLoading(true);
  const treeData = ref();
  const treeData1 = ref();
  const currentCompany = ref();
  const selectKeys = ref([]);
  const jigoulist = ref();
  const treeKey = ref(0); // 新增用于控制 a-tree 重新渲染的 key

  // 传递给子组件的表单数据
  const sonFormType = ref<any>();
  const sonFormType1 = ref<any>();
  async function getDeptList() {
    const resa = await getAllRole();
    getDept({
      page_on: 1,
      page_size: 1000,
      dept_org_id: currentCompany.value,
    })
      .then((res) => {
        setLoading(true);
        treeData.value = transformDeptTree(res.data.list, '0-0', 'dept_id');
        treeData1.value = transformDeptTreeSelect(
          res.data.list,
          'dept_id',
          'dept_id'
        );
        sonFormType.value = [
          {
            name: 'user_name',
            label: '用户名称',
            type: 'a-input',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_true_name',
            label: '真实姓名',
            type: 'a-input',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_dept_id',
            label: '所属部门',
            type: 'a-tree-select',
            placeholder: '请选择',
            fieldProps: {
              span: 24,
              data: treeData1.value ? treeData1.value : [],
            },
          },
          {
            name: 'user_password',
            label: '用户密码',
            type: 'a-input-password',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_confirm_password',
            label: '确认密码',
            type: 'a-input-password',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_mobile',
            label: '用户手机',
            type: 'a-input-number',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_wechat',
            label: '用户微信',
            type: 'a-input',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_gender',
            label: '用户性别',
            type: 'a-select',
            placeholder: '请选择',
            fieldProps: {
              span: 24,
            },
            selectOptions: [
              {
                value: 1,
                label: '未知',
              },
              {
                value: 2,
                label: '男',
              },
              {
                value: 3,
                label: '女',
              },
            ],
          },
          {
            name: 'user_sort',
            label: '用户排序',
            type: 'a-input-number',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_remarks',
            label: '备注信息',
            type: 'a-textarea',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'role_ids',
            label: '所属角色',
            type: 'a-select',
            placeholder: '请选择',
            fieldProps: {
              textAlign: 'left',
              allowSearch: true,
              span: 24,
              multiple: true,
              fieldNames: { value: 'role_id', label: 'role_name' },
            },
            selectOptions: resa.data,
          },
        ];
        sonFormType1.value = [
          {
            name: 'user_name',
            label: '用户名称',
            type: 'a-input',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_true_name',
            label: '真实姓名',
            type: 'a-input',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_dept_id',
            label: '所属部门',
            type: 'a-tree-select',
            placeholder: '请选择',
            fieldProps: {
              span: 24,
              data: treeData1.value ? treeData1.value : [],
            },
          },
          {
            name: 'user_mobile',
            label: '用户手机',
            type: 'a-input-number',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_wechat',
            label: '用户微信',
            type: 'a-input',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_gender',
            label: '用户性别',
            type: 'a-select',
            placeholder: '请选择',
            fieldProps: {
              span: 24,
            },
            selectOptions: [
              {
                value: 1,
                label: '未知',
              },
              {
                value: 2,
                label: '男',
              },
              {
                value: 3,
                label: '女',
              },
            ],
          },
          {
            name: 'user_sort',
            label: '用户排序',
            type: 'a-input-number',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'user_remarks',
            label: '备注信息',
            type: 'a-textarea',
            fieldProps: {
              span: 24,
            },
          },
          {
            name: 'role_ids',
            label: '所属角色',
            type: 'a-select',
            placeholder: '请选择',
            fieldProps: {
              textAlign: 'left',
              allowSearch: true,
              span: 24,
              multiple: true,
              fieldNames: { value: 'role_id', label: 'role_name' },
            },
            selectOptions: resa.data,
          },
        ];
      })
      .finally(() => {
        setLoading(false);
      });
  }
  onMounted(() => {
    getOrgAll().then((res: any) => {
      jigoulist.value = res.data;
      getDeptList();
    });
  });

  // 方法定义调整
  function handleNodeSelect(event: Event, data: any) {
    currentKeys.value = data.node.id; // 存储第一个选中节点的key
    proTableRef.value?.setRefresh();
  }

  function handleSubmit(form: any) {
    const id = findIdByKey(treeData.value, form.dept_parent_id);
    form.dept_parent_id = id;
    editDept(
      omit(form, [
        'dept_org_name',
        'dept_parent_name',
        'dept_leader_name',
        'dept_competent_id_name',
      ])
    ).then((res) => {
      getDeptList();
      Message.success(res.msg);
    });
  }

  function changeSelect(e: any) {
    currentCompany.value = e;
    getDeptList();
  }
  const currentParams = ref({});
  async function request(params: any) {
    const res = await getUserList({
      ...params,
      user_dept_id: currentKeys.value,
    });
    return {
      data: res.data,
    };
  }

  const SearchType = ref([
    {
      name: 'user_name',
      label: '用户名称',
      type: 'a-input',
      fieldProps: {
        span: 8,
      },
    },
    {
      name: 'user_true_name',
      label: '真实姓名',
      type: 'a-input',
      fieldProps: {
        span: 8,
      },
    },
    {
      name: 'user_mobile',
      label: '用户电话',
      type: 'a-input',
      fieldProps: {
        span: 8,
      },
    },
    {
      name: 'user_gender',
      label: '用户性别',
      type: 'a-select',
      fieldProps: {
        span: 8,
      },
      selectOptions: [
        {
          value: 1,
          label: '',
        },
        {
          value: 2,
          label: '男',
        },
        {
          value: 3,
          label: '女',
        },
      ],
    },
    {
      name: 'user_state',
      label: '用户状态',
      type: 'a-select',
      slotName: 'status',
      fieldProps: {
        span: 8,
      },
      selectOptions: [
        {
          value: 1,
          label: '正常',
          status: 'success',
        },
        {
          value: 2,
          label: '禁用',
          status: 'danger',
        },
        {
          value: 3,
          label: '离职',
          status: 'normal',
        },
      ],
    },
  ]);
  const tableType = [
    { dataIndex: 'user_id', slotName: 'id' },
    {
      title: '用户名称',
      dataIndex: 'user_name',
    },
    {
      title: '真实姓名',
      dataIndex: 'user_true_name',
      align: 'center',
    },
    {
      title: '部门',
      dataIndex: 'user_dept_name',
      align: 'center',
    },
    {
      title: '性别',
      dataIndex: 'user_gender',
      slotName: 'sex',
      align: 'center',
    },
    {
      title: '手机',
      dataIndex: 'user_mobile',
      align: 'center',
    },
    {
      title: '微信',
      dataIndex: 'user_wechat',
    },
    {
      title: '备注',
      dataIndex: 'user_remarks',
    },
    {
      title: '状态',
      dataIndex: 'user_state',
      slotName: 'status',
      options: [
        {
          status: 'success',
          value: 1,
          label: '正常',
        },
        {
          status: 'danger',
          value: 2,
          label: '禁用',
        },
        {
          status: 'normal',
          value: 3,
          label: '离职',
        },
      ],
    },
    {
      title: '操作',
      width: 130,
      fixed: 'right',
      slotName: 'operations',
      menus: [
        {
          name: '编辑',
          onClick: (record: any) => {
            visible1.value = true;
            currentParams.value = {
              user_id: record.user_id,
            };
          },
        },
        {
          name: '重置密码',
          onClick: (record: any) => {
            visible2.value = true;
            currentParams.value = {
              user_id: record.user_id,
            };
          },
        },
        {
          name: '删除',
          onClick: (record: any) => {
            delectUser({
              user_ids: [record.user_id],
            }).then((res: any) => {
              proTableRef.value?.setRefresh();
              Message.success('删除成功！');
            });
          },
        },
      ],
    },
  ];

  // 清空部门选中，重置表格
  function resetTable() {
    currentKeys.value = '';
    selectKeys.value = [];
    treeKey.value++; // 更新 key 值，强制 a-tree 重新渲染
    proTableRef.value?.setRefresh();
  }
  // 重置密码密码
  const handleResetPassword = async () => {
    // 校验选中状态[6](@ref)
    if (proTableRef.value?.selectedKeys.length === 0) {
      Message.warning('请至少选择一个用户进行操作');
      return;
    }

    // 二次确认弹窗
    Modal.confirm({
      title: '危险操作确认',
      content: `确定要重置用户的密码吗？`,
      okText: '确认重置',
      cancelText: '取消',
      async onOk() {
        //   try {
        //     // 调用重置接口（假设接口格式与delectUser一致）
        //     await resetPwd({ user_ids: selectedUserIds.value });
        //     Message.success('密码重置成功');
        //     proTableRef.value?.setRefresh(); // 刷新表格[3](@ref)
        //   } catch (error) {
        //     Message.error('操作失败，请检查网络连接');
        //   }
      },
    });
  };
  function handleRefresh() {
    loading.value = true;
    proTableRef.value?.setRefresh();
    loading.value = false;
  }
</script>

<template>
  <div class="container" style="width: 110%">
    <a-row gutter="5">
      <a-col span="5">
        <a-card title="部门列表">
          <a-select
            v-model="currentCompany"
            placeholder="请选择机构"
            :options="jigoulist"
            :field-names="{ value: 'org_id', label: 'org_name' }"
            @change="changeSelect"
          >
            <template #prefix> 当前机构 </template>
          </a-select>
          <div style="display: flex; align-items: center; margin-top: 10px">
            <a-spin
              style="
                margin: 0 auto;
                margin-top: 20px;
                min-height: 50px;
                justify-content: center;
              "
              v-if="loading"
              dot
            />
            <a-tree
              v-else
              default-expand-all
              blockNode
              :data="treeData"
              v-model:checked-keys="selectKeys"
              @select="handleNodeSelect"
              :check-strictly="true"
              :key="treeKey"
            />
          </div>
          <template #extra>
            <a-tooltip content="重置">
              <div @click="resetTable">
                <icon-loop size="20" />
              </div>
            </a-tooltip>
          </template>
        </a-card>
      </a-col>
      <a-col span="17">
        <pro-table
          ref="proTableRef"
          :formType="SearchType"
          title="用户列表"
          :request="request"
          :tableType="tableType"
          rowKey="user_id"
          showRows
        >
          <template #btns>
            <a-button
              type="primary"
              @click="
                () => {
                  visible = true;
                }
              "
            >
              <template #icon>
                <icon-user-add />
              </template>
              添加用户
            </a-button>
            <a-button @click="handleResetPassword">
              <template #icon>
                <icon-lock />
              </template>
              重置密码
            </a-button>
          </template>
        </pro-table>
        <div v-if="false" class="formContent" style="display: flex">
          <a-spin
            style="
              margin: 0 auto;
              margin-top: 20px;
              min-height: 50px;
              justify-content: center;
            "
            v-if="loading"
            dot
          />
          <pro-form
            v-if="!loading && currentKeys"
            :btnTitle="['修改']"
            :form-json="formType"
            :form-data="formData"
            @search="handleSubmit"
          ></pro-form>
          <a-empty v-if="!loading && !currentKeys" />
        </div>
      </a-col>
    </a-row>
    <Add
      v-if="visible"
      v-model:visible="visible"
      :form-type="sonFormType"
      @refresh="handleRefresh"
    />
    <Edit
      v-if="visible1"
      v-model:visible="visible1"
      :form-type="sonFormType1"
      :params="currentParams"
      @refresh="handleRefresh"
    />
    <Rpwd v-if="visible2" v-model:visible="visible2" :params="currentParams" />
  </div>
</template>

<style scoped lang="less">
  .container {
    height: 100%;
    background: #f2f3f5;
  }

  .formContent {
    width: 100%;
  }
  // tree的css样式
  :deep(.icon) {
    width: 1.2em !important;
    height: 1.2em !important;
  }

  :deep(.arco-tree-node-title-text) {
    font-size: 12px;
    width: 140px;
    overflow: hidden; /* 隐藏溢出内容 */
    white-space: nowrap; /* 禁止换行 */
    text-overflow: ellipsis; /* 显示省略号 */
  }

  :deep(.arco-tree-node-indent-block) {
    width: 0px !important;
  }
</style>
